package com.dotflat.dashboard.service.impl;

import com.dotflat.dashboard.service.DashboardService;
import com.dotflat.dashboard.vo.*;
import com.dotflat.util.UuidUtil;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.domain.Children;
import com.matt.domain.TargetObject;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.ClassesRepository;
import com.matt.repository.TargetObjectRepository;
import com.matt.repository.base.BaseNativeSqlRepository;
import com.matt.service.remoteCall.DTO.SsoAreaDTO;
import com.matt.service.remoteCall.SsoCallService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class DashboardServiceImpl  implements DashboardService {

    @Autowired
    private BaseNativeSqlRepository baseNativeSqlRepository;

    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private ClassesRepository classesRepository;

    @Autowired
    private TargetObjectRepository targetObjectRepository;

    @Autowired
    private SsoCallService ssoCallService;

    @Override
    public InformationVO information(List<SsoAreaDTO> areaDTOList) {
        InformationVO information = new InformationVO();
        information.setAreaCount(areaDTOList.size());

        List<String> list = areaDTOList.stream().map(k->k.getId()).collect(Collectors.toList());

        Integer count = childrenRepository.getCount(-1,list);
        //总学生数量
        information.setChildrenCount(count);

        int maleCount = childrenRepository.getCount(1,list);
        //总男学生数量
        information.setMaleCount(maleCount);

        int femaleCount = childrenRepository.getCount(0,list);
        //总女学生数量
        information.setFemaleCount(femaleCount);

        int classCount = classesRepository.getAreaIdCount(list);
        //总班级数量
        information.setClassCount(classCount);

        return information;
    }

    @Override
    public List<Children> findAllByStatusAndAreaIdIn(Integer status, String[] areaIds) {
        return childrenRepository.findAllByStatusAndAreaIdIn(status,areaIds);
    }

//
//    @Override
//    public  List<GradeCountVO>  grade(List<String> areaIds) {
//        String ids = UuidUtil.getString(areaIds);
//        String sql = "SELECT tt.id,tt.`name`,IFNULL(t.childrenCount,'0') as childrenCount ,IFNULL(t.classesCount,'0') as classesCount  FROM target_object tt LEFT JOIN   " +
//                " (SELECT tt.id, tt.name ,SUM(tt.childrenCount) childrenCount,COUNT(tt.classesId) classesCount FROM   " +
//                " (SELECT tt.id, tt.name ,COUNT(tt.childrenId) childrenCount,tt.classesId  FROM   " +
//                " (SELECT tt.id,tt.name,cc.childrenId,cc.classesId FROM target_object tt LEFT JOIN classes c  ON c.targetObjectId = tt.id    " +
//                "  LEFT JOIN rel_classes_children cc ON c.id = cc.classesId   " +
//                "  WHERE c.areaId in ("+ids+")   AND cc.childrenId  IS NOT NULL  GROUP BY cc.childrenId) tt  " +
//                " GROUP BY tt.classesId) tt  GROUP BY tt.id) t  ON tt.id = t.id WHERE tt.`code` > 0";
//        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
//        List<GradeCountVO> list = new ArrayList<>();
//        for (int i = 0; i <objects.size() ; i++) {
//            GradeCountVO gradeCountVO = new GradeCountVO();
//            gradeCountVO.setId(objects.get(i)[0].toString());
//            gradeCountVO.setName(objects.get(i)[1].toString());
//            gradeCountVO.setChildrenCount(Integer.parseInt(objects.get(i)[2].toString()));
//            gradeCountVO.setClassesCount(Integer.parseInt(objects.get(i)[3].toString()));
//            list.add(gradeCountVO);
//        }
//
//
//        String sql1 = "SELECT COUNT(cc.id),ifnull(SUM(cc.cid),0)  FROM  " +
//                "(SELECT c.id,c.aid,COUNT(c1.id) cid FROM  `children`  c  LEFT JOIN rel_classes_children rcc on rcc.childrenId = c.id  LEFT JOIN classes c1  on c1.id = rcc.classesId " +
//                "WHERE c1.category = 2 and c.aid in ("+ids+")  GROUP BY c.id)  cc ";
//        List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql1);
//        GradeCountVO gradeCountVO = new GradeCountVO();
//        gradeCountVO.setId("");
//        gradeCountVO.setName("早教");
//        gradeCountVO.setChildrenCount(Integer.parseInt(objects1.get(0)[0].toString()));
//        gradeCountVO.setClassesCount(Integer.parseInt(objects1.get(0)[1].toString()));
//        list.add(gradeCountVO);
//       return list;
//    }




    @Override
    public List<GradeCountVO> grade(List<String> areaIds) {
        String ids = UuidUtil.getString(areaIds);

        // 修复第一个SQL查询，添加ANY_VALUE()函数处理非聚合列
        String sql = "SELECT ANY_VALUE(tt.id) AS id, ANY_VALUE(tt.`name`) AS name, "
                + "IFNULL(ANY_VALUE(t.childrenCount),'0') AS childrenCount, "
                + "IFNULL(ANY_VALUE(t.classesCount),'0') AS classesCount "
                + "FROM target_object tt LEFT JOIN "
                + "(SELECT tt.id, ANY_VALUE(tt.name) AS name, "
                + "SUM(tt.childrenCount) AS childrenCount, "
                + "COUNT(tt.classesId) AS classesCount "
                + "FROM "
                + "(SELECT tt.id, ANY_VALUE(tt.name) AS name, "
                + "COUNT(tt.childrenId) AS childrenCount, "
                + "ANY_VALUE(tt.classesId) AS classesId "
                + "FROM "
                + "(SELECT tt.id, ANY_VALUE(tt.name) AS name, "
                + "cc.childrenId, ANY_VALUE(cc.classesId) AS classesId "
                + "FROM target_object tt "
                + "LEFT JOIN classes c ON c.targetObjectId = tt.id "
                + "LEFT JOIN rel_classes_children cc ON c.id = cc.classesId "
                + "WHERE c.areaId IN (" + ids + ") "
                + "AND cc.childrenId IS NOT NULL "
                + "GROUP BY cc.childrenId) tt "
                + "GROUP BY tt.classesId) tt "
                + "GROUP BY tt.id) t ON tt.id = t.id "
                + "WHERE tt.`code` > 0 "
                + "GROUP BY tt.id";  // 添加最终的GROUP BY

        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        List<GradeCountVO> list = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            GradeCountVO gradeCountVO = new GradeCountVO();
            gradeCountVO.setId(objects.get(i)[0].toString());
            gradeCountVO.setName(objects.get(i)[1].toString());
            gradeCountVO.setChildrenCount(Integer.parseInt(objects.get(i)[2].toString()));
            gradeCountVO.setClassesCount(Integer.parseInt(objects.get(i)[3].toString()));
            list.add(gradeCountVO);
        }

        // 修复第二个SQL查询，确保符合GROUP BY规则
        String sql1 = "SELECT COUNT(cc.id) AS count, IFNULL(SUM(cc.cid), 0) AS sum "
                + "FROM ("
                + "SELECT c.id, c.aid, COUNT(c1.id) AS cid "
                + "FROM `children` c "
                + "LEFT JOIN rel_classes_children rcc ON rcc.childrenId = c.id "
                + "LEFT JOIN classes c1 ON c1.id = rcc.classesId "
                + "WHERE c1.category = 2 AND c.aid IN (" + ids + ") "
                + "GROUP BY c.id, c.aid"  // 添加所有非聚合列到GROUP BY
                + ") cc";

        List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql1);
        GradeCountVO gradeCountVO = new GradeCountVO();
        gradeCountVO.setId("");
        gradeCountVO.setName("早教");
        gradeCountVO.setChildrenCount(Integer.parseInt(objects1.get(0)[0].toString()));
        gradeCountVO.setClassesCount(Integer.parseInt(objects1.get(0)[1].toString()));
        list.add(gradeCountVO);

        return list;
    }



    @Override
    public List<Map> getAreaIdCountList(List<String> areaIds) {
        String ids = UuidUtil.getString(areaIds);
        String sql = "SELECT areaId,COUNT(id) FROM `classes` where areaId in ("+ids+") GROUP BY  areaId";
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        List<Map> list = new ArrayList<>();
        for (int i = 0; i <objects.size() ; i++) {
            Map map = new HashMap();
            map.put("areaId",objects.get(i)[0].toString());
            map.put("count",Integer.parseInt(objects.get(i)[1].toString()));
            list.add(map);
        }
        return list;
    }

    @Override
    public List<ClassesCountVO> getClassCount(List<String> areaIds) {
        String ids = UuidUtil.getString(areaIds);
        String sql = "SELECT tt.id,tt.name, c.areaId,COUNT(rcc.childrenId)  FROM target_object tt LEFT JOIN classes c  ON c.targetObjectId = tt.id " +
                "  LEFT JOIN rel_classes_children rcc ON  rcc.classesId = c.id  LEFT JOIN children c1 ON rcc.childrenId = c1.id " +
                "    WHERE c1.`status` =1  AND tt.`code`> 0 and c.areaId in  ("+ids+") GROUP BY c.areaId";
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);


        List<ClassesCountVO> list = new ArrayList<>();
        for (int i = 0; i <objects.size() ; i++) {
            ClassesCountVO classesCountVO = new ClassesCountVO();
            classesCountVO.setId(objects.get(i)[0].toString());
            classesCountVO.setName(objects.get(i)[1].toString());
            classesCountVO.setAreaId(objects.get(i)[2].toString());
            classesCountVO.setChildrenCount(Integer.parseInt(objects.get(i)[3].toString()));
            list.add(classesCountVO);
        }
        return list;
    }

    @Override
    public List<TargetObject> getAll() {
        List<TargetObject>  list1 = targetObjectRepository.findAllCode();
        return list1;
    }

    @Override
    public List<Map> getAreaIdChildrenCount(List<String> areaIds) {
        String ids = UuidUtil.getString(areaIds);
        String sql = "SELECT c.id,c.aid,cei.checkStatus,IFNULL(cei.checkTime,'')  FROM `children`  c INNER JOIN children_extend_info cei  on cei.childrenId = c.id  " +
                " where c.status = 1 and  c.aid in ("+ids+") ";
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        List<Map> list = new ArrayList<>();
        for (int i = 0; i <objects.size() ; i++) {
            Map map = new HashMap();
            map.put("id",objects.get(i)[0].toString());
            map.put("areaId",objects.get(i)[1].toString());
            map.put("checkStatus",objects.get(i)[2].toString());
            map.put("checkTime",objects.get(i)[3].toString());
            list.add(map);
        }
        return list;
    }

    @Override
    public List<ClassTypeCountVO> classTypeCount(List<String> areaIds) {
        String ids = UuidUtil.getString(areaIds);

        List<ClassTypeCountVO> list = new ArrayList<>();

        String sql = "SELECT COUNT(*)  FROM (SELECT c.id FROM children c LEFT JOIN rel_classes_children rcc on rcc.childrenId = c.id LEFT JOIN classes cs  on cs.id = rcc.classesId \n" +
                "where cs.category = 1 and  c.aid in ("+ids+") GROUP BY c.id ) a";
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        int childrenCount1 = Integer.parseInt(String.valueOf(objects.get(0)));

        String sql1 = "SELECT COUNT(*) FROM `classes` where  category = 1 and  areaId in ("+ids+") ";
        List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql1);
        int classCount1 = Integer.parseInt(String.valueOf(objects1.get(0)));

        ClassTypeCountVO typeCount = new ClassTypeCountVO();
        typeCount.setClassCount(classCount1);
        typeCount.setChildrenCount(childrenCount1);
        typeCount.setName("托班");
        list.add(typeCount);

        String sql11 = "SELECT COUNT(*)  FROM (SELECT c.id FROM children c LEFT JOIN rel_classes_children rcc on rcc.childrenId = c.id LEFT JOIN classes cs  on cs.id = rcc.classesId \n" +
                "where cs.category = 2 and  c.aid in ("+ids+") GROUP BY c.id ) a";
        List<Object[]> objects11 = baseNativeSqlRepository.sqlArrayList(sql11);
        int childrenCount2 = Integer.parseInt(String.valueOf(objects11.get(0)));

        String sql12 = "SELECT COUNT(*) FROM `classes` where  category = 2 and  areaId in ("+ids+") ";
        List<Object[]> objects12 = baseNativeSqlRepository.sqlArrayList(sql12);
        int classCount2 = Integer.parseInt(String.valueOf(objects12.get(0)));
        ClassTypeCountVO typeCount1 = new ClassTypeCountVO();
        typeCount1.setClassCount(classCount2);
        typeCount1.setChildrenCount(childrenCount2);
        typeCount1.setName("早教");
        list.add(typeCount1);
        return list;
    }


    @Override
    public List<AreaClassTypeCountVO> areaClassTypeCount(List<String> areaIds) {
        String ids = UuidUtil.getString(areaIds);

        List<AreaClassTypeCountVO> list = new ArrayList<>();

        String sql = "SELECT COUNT(a.id),a.aid  FROM (SELECT c.id,c.aid FROM children c LEFT JOIN rel_classes_children rcc on rcc.childrenId = c.id " +
                "LEFT JOIN classes cs  on cs.id = rcc.classesId where cs.category = 1 and  c.aid in ("+ids+")  GROUP BY c.id ) a GROUP BY a.aid  ";
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);

        String sql1 = "SELECT COUNT(id),areaId FROM `classes` where  category = 1  and  areaId in ("+ids+")  GROUP BY areaId  ";
        List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql1);

        String sql11 =  "SELECT COUNT(a.id),a.aid  FROM (SELECT c.id,c.aid FROM children c LEFT JOIN rel_classes_children rcc on rcc.childrenId = c.id " +
                "LEFT JOIN classes cs  on cs.id = rcc.classesId where cs.category = 2 and  c.aid in ("+ids+")  GROUP BY c.id ) a GROUP BY a.aid  ";
        List<Object[]> objects11 = baseNativeSqlRepository.sqlArrayList(sql11);

        String sql12 = "SELECT COUNT(id),areaId FROM `classes` where  category = 2  and  areaId in ("+ids+")  GROUP BY areaId  ";
        List<Object[]> objects12 = baseNativeSqlRepository.sqlArrayList(sql12);


        for (int i = 0; i <areaIds.size() ; i++) {
            AreaClassTypeCountVO areaClassTypeCountVO = new AreaClassTypeCountVO();
            areaClassTypeCountVO.setAreaId(areaIds.get(i));

            List<ClassTypeCountVO> list1 = new ArrayList<>();
            ClassTypeCountVO classTypeCount = new ClassTypeCountVO();
            classTypeCount.setName("托班");
            for (int j = 0; j < objects.size(); j++) {

                if (StringUtils.equals(areaIds.get(i),objects.get(j)[1].toString())){
                    classTypeCount.setChildrenCount(Integer.parseInt(objects.get(j)[0].toString()));
                }
                for (int k = 0; k <objects1.size() ; k++) {
                    if (StringUtils.equals(areaIds.get(i),objects1.get(k)[1].toString())){
                        classTypeCount.setClassCount(Integer.parseInt(objects1.get(k)[0].toString()));
                    }
                }
            }
            list1.add(classTypeCount);
            ClassTypeCountVO classTypeCount_1 = new ClassTypeCountVO();
            classTypeCount_1.setName("早教");
            for (int j = 0; j < objects11.size(); j++) {
                if (StringUtils.equals(areaIds.get(i),objects11.get(j)[1].toString())){
                    classTypeCount_1.setChildrenCount(Integer.parseInt(objects11.get(j)[0].toString()));
                }
                for (int k = 0; k <objects12.size() ; k++) {
                    if (StringUtils.equals(areaIds.get(i),objects12.get(k)[1].toString())){
                        classTypeCount_1.setClassCount(Integer.parseInt(objects12.get(k)[0].toString()));
                    }
                }
            }
            list1.add(classTypeCount_1);
            areaClassTypeCountVO.setList(list1);
            list.add(areaClassTypeCountVO);
        }
        return list;
    }


    @Override
    public AreaClassListVO getAreaClass(String areaId) {

        String sql = "SELECT a.id,a.`name`,a.classCount,IFNULL(b.childrenCount,0)   FROM (SELECT COUNT(c.id) as classCount ,t.`name`,t.id   FROM target_object  t LEFT JOIN  classes c on t.id  = c.targetObjectId \n" +
                " WHERE t.`code` != 0  and c.areaId = '"+areaId+"' GROUP BY t.id) a LEFT JOIN  " +
                "(SELECT COUNT(ch.id) childrenCount ,t.`name`,t.id   FROM target_object  t LEFT JOIN  classes c on t.id  = c.targetObjectId \n" +
                "  LEFT JOIN rel_classes_children rcc ON rcc.classesId = c.id LEFT JOIN children ch on ch.id = rcc.childrenId \n" +
                " WHERE t.`code` != 0 and ch.status = 1  and c.areaId = '"+areaId+"'  GROUP BY t.id ) b  ON a.id = b.id ";
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        AreaClassListVO areaClassListVO = new AreaClassListVO();
        int areaClassCount = 0;
        List<AreaClassVO> areaClassList = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            AreaClassVO areaClass = new AreaClassVO();
            areaClass.setClassName( objects.get(i)[1].toString());
            areaClass.setClassCount(Integer.parseInt(objects.get(i)[2].toString()));
            areaClass.setChildrenCount(Integer.parseInt(objects.get(i)[3].toString()));
            areaClassCount+=Integer.parseInt(objects.get(i)[2].toString());
            areaClassList.add(areaClass);
        }

        String sql1 = "SELECT COUNT(ch.id) FROM children ch LEFT JOIN rel_classes_children rcc on rcc.childrenId = ch.id \n" +
                "  LEFT JOIN classes c ON rcc.classesId = c.id \n" +
                " WHERE   c.category =2 and ch.status = 1  and c.areaId = '"+areaId+"'" ;
        List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql1);
        int childrenCount = Integer.parseInt(String.valueOf(objects1.get(0)));


        String sql2 = "SELECT COUNT(c.id) FROM  classes c  WHERE   c.category =2  and c.areaId = '"+areaId+"'" ;
        List<Object[]> objects2 = baseNativeSqlRepository.sqlArrayList(sql2);
        int classCount = Integer.parseInt(String.valueOf(objects2.get(0)));

        AreaClassVO areaClass = new AreaClassVO();
        areaClass.setClassName( "早教");
        areaClass.setClassCount(classCount);
        areaClass.setChildrenCount(childrenCount);
        areaClassList.add(areaClass);
        areaClassCount+=classCount;
        areaClassListVO.setAreaClassCount(areaClassCount);

        Integer count1 = childrenRepository.getGenderCount(0,areaId);
        Integer count2 = childrenRepository.getGenderCount(1,areaId);
        ChildrenGenderCountVO childrenGenderCountVO = new ChildrenGenderCountVO();
        childrenGenderCountVO.setGender("女");
        childrenGenderCountVO.setChildrenCount(count1);
        ChildrenGenderCountVO childrenGenderCountVO1 = new ChildrenGenderCountVO();
        childrenGenderCountVO1.setGender("男");
        childrenGenderCountVO1.setChildrenCount(count2);

        List<ChildrenGenderCountVO> childrenGenderCountList = new ArrayList<>();
        childrenGenderCountList.add(childrenGenderCountVO);
        childrenGenderCountList.add(childrenGenderCountVO1);
        areaClassListVO.setAreaChildrenCount(count1+count2);
        areaClassListVO.setChildrenGenderCountList(childrenGenderCountList);

        areaClassListVO.setAreaClassList(areaClassList);


        List<StaffDTO> list1 = ssoCallService.getStaffDTOList(areaId);
        areaClassListVO.setAreaStaffCount(list1.size());
        return areaClassListVO;
    }

    @Override
    public List<ChildrenCheckVO> getChildrenCheck(List<String> areaIds, String date) {
        String ids = UuidUtil.getString(areaIds);

        String sql1 = "SELECT cr.childrenId,c.aid,c.name ,DATE_FORMAT(cr.checkInTime, '%Y-%m-%d'),cr.`status` ,IFNULL(cr.specialRecord,'') " +
                "FROM  children c LEFT JOIN `check_record`  cr on c.id = cr.childrenId WHERE " +
                " DATE_FORMAT(cr.checkInTime, '%Y-%m') = DATE_FORMAT('"+date+"', '%Y-%m')  and  c.aid in ("+ids+")" +
                " GROUP BY cr.childrenId,DATE_FORMAT(cr.checkInTime, '%Y-%m-%d') " ;
        List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql1);


        List<ChildrenCheckVO> ret = objects1.stream().map(o->{
            ChildrenCheckVO vo = new ChildrenCheckVO();
            vo.setChildrenId(o[0].toString());
            vo.setAreaId(o[1].toString());
            vo.setChildrenName(o[2].toString());
            vo.setCheckInTime(o[3].toString());
            vo.setStatus(Integer.parseInt(o[4].toString()));
            vo.setHealthyStatus(Integer.valueOf(o[5].toString()));
            return vo;
        }).collect(Collectors.toList());
        return ret;
    }

    @Override
    public List<ChildrenCheckVO> getChildrenClassCheck(List<String> childrenIds, String beginAt, String endAt) {
        if (CollectionUtils.isEmpty(childrenIds)) {
            return Collections.emptyList();
        }

        String ids = UuidUtil.getString(childrenIds);

        // 1. 修复SQL：补充空格，去掉GROUP BY，优化时间范围（避免过滤出园记录）
        String sql1 = "SELECT " +
                "cr.childrenId, " +          // 0: 学生ID
                "c.aid, " +                  // 1: 园区ID
                "c.name, " +                 // 2: 学生姓名
                "cr.checkInTime, " +         // 3: 完整入园时间（含时分秒）
                "cr.`status`, " +            // 4: 考勤状态（1=入园，6=早退）
                "IFNULL(cr.healthyStatus, '0'), " +  // 5: 健康状态（默认0）
                "cr.checkOutTime " +         // 6: 完整出园时间（含时分秒）→ 末尾加空格，避免语法错误
                "FROM children c " +         // 修复：与前面的cr.checkOutTime有空格
                "LEFT JOIN `check_record` cr ON c.id = cr.childrenId " +
                "WHERE " +
                // 时间范围：同时包含checkInTime和checkOutTime，避免漏查
                "(DATE_FORMAT(cr.checkInTime, '%Y-%m-%d %H:%i:%S') BETWEEN DATE_FORMAT('" + beginAt + "', '%Y-%m-%d %H:%i:%S') " +
                "AND DATE_FORMAT('" + endAt + "', '%Y-%m-%d %H:%i:%S')) " +
                "AND c.id IN (" + ids + ") " +
                // 排序：同学生按时间倒序，确保出园记录（status=6）在后面，便于后续保留
                "ORDER BY cr.childrenId, cr.checkInTime DESC, cr.checkOutTime DESC";

        // 2. 执行查询（捕获SQL异常，便于调试）
        List<Object[]> objects1;
        try {
            objects1 = baseNativeSqlRepository.sqlArrayList(sql1);
        } catch (Exception e) {
            log.error("SQL执行失败，SQL:{}", sql1, e);
            throw new RuntimeException("考勤记录查询失败", e);
        }

        // 3. 字段映射：严格按SELECT顺序赋值，处理null值
        List<ChildrenCheckVO> ret = objects1.stream().map(o -> {
            ChildrenCheckVO vo = new ChildrenCheckVO();
            // 安全赋值：避免null导致的空指针
            vo.setChildrenId(getSafeString(o[0]));       // 0: 学生ID
            vo.setAreaId(getSafeString(o[1]));           // 1: 园区ID
            vo.setChildrenName(getSafeString(o[2]));     // 2: 学生姓名
            vo.setCheckInTime(getSafeString(o[3]));      // 3: 入园时间
            vo.setStatus(getSafeInteger(o[4]));          // 4: 状态（6=早退）
            vo.setHealthyStatus(getSafeInteger(o[5]));   // 5: 健康状态
            vo.setCheckOutTime(getSafeString(o[6]));     // 6: 出园时间（核心：终于能拿到值了）

            // 日志：验证出园记录是否被查询到
            log.info("查询到考勤记录：childrenId={}, status={}, checkInTime={}, checkOutTime={}",
                    vo.getChildrenId(), vo.getStatus(), vo.getCheckInTime(), vo.getCheckOutTime());
            return vo;
        }).collect(Collectors.toList());

        return ret;
    }

    // 辅助方法：安全处理null值（避免空指针）
    private String getSafeString(Object obj) {
        return obj != null ? obj.toString() : null;
    }

    private Integer getSafeInteger(Object obj) {
        if (obj == null) return 0;
        try {
            if (obj instanceof Number) {
                return ((Number) obj).intValue();
            }
            return Integer.parseInt(obj.toString());
        } catch (Exception e) {
            log.error("类型转换失败：{}→Integer", obj, e);
            return 0;
        }
    }



    @Override
    public List<ChildrenCheckVO> getCheckRecordsByChildrenId(List<String> childrenIds, Date beginAt, Date endAt) {

        List params = new ArrayList();
        params.add(beginAt);
        params.add(endAt);
        params.add(childrenIds);

        String sql = "SELECT cr.childrenId, cr.groupFlag as checkInTime, cr.`status`, cr.healthyStatus " +
                " FROM `check_record`  cr " +
                " WHERE cr.checkInTime >= :1 AND  cr.checkInTime <= :2 and cr.childrenId in (:3)" +
                " GROUP BY cr.groupFlag " ;
        List<ChildrenCheckVO> ret = baseNativeSqlRepository.sqlObjectList(sql, params, ChildrenCheckVO.class);

        return ret;
    }
}